package com.nyist.myticket.web.interceptor;


import com.nyist.myticket.core.factory.GenerateCodeFactory;
import com.nyist.myticket.core.utils.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * *拦截器, 计算请求时间
 *
 * @author yangxiaogen
 * @date 2022/3/2 16:28
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {

    public final static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    private ThreadLocal<Long> timeThreadLocal = new ThreadLocal<Long>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("拦截器被调用了....preHandle");
        logger.info("================================  start   ================================");
        String logTraceId = request.getHeader(SysConstant.LOG_TRACE_ID);
        if (StringUtils.isBlank(logTraceId)) {
            Long snowflakeId = GenerateCodeFactory.snowflakeId();
            logTraceId = snowflakeId.toString();
        }

        MDC.put(SysConstant.LOG_TRACE_ID, logTraceId);

        long beginTime = System.currentTimeMillis(); // 1、开始时间
        timeThreadLocal.set(beginTime);              // 线程绑定变量（该数据只有当前请求的线程可见）
        return true;      // 继续流程
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        logger.info("拦截器被调用了....postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.info("拦截器被调用了....afterCompletion");

        long endTime = System.currentTimeMillis();// 2、结束时间
        long beginTime = timeThreadLocal.get();// 得到线程绑定的局部变量（开始时间）

        String requestURI = request.getRequestURI();

        long requestTime = endTime - beginTime;
        if (requestTime > 500) {// 此处认为处理时间超过500毫秒的请求为慢请求
            logger.warn(requestURI + " 比较耗时：" + requestTime);
        } else {
            logger.info("=====>请求地址为:" + requestURI + "  耗时为: {}", requestTime);
        }

        MDC.remove(SysConstant.LOG_TRACE_ID);
        logger.info("================================  end   ================================");
    }

}
